//
// Created by liushuai on 18-8-23.
//

#include "Tree.h"
#include <iostream>
Tree::Tree(int tsize,int &proot)
{
    size = tsize;
    pTree = new int[size];
    pTree[0] = proot;
}
Tree::~Tree() {
    delete [] pTree;
}
bool Tree::addNode(int nodeIndex, int direction, int &pNode) {
    if(nodeIndex<0||nodeIndex>size)
    {
        std::cout<<"插入位置不合法"<<std::endl;
        return false;
    }
    else if(pTree[nodeIndex] == 0)
    {
        std::cout<<"该节点位置为空"<<"\n";
        return false;
    }
    else
    {
        int insertLoc = 2*nodeIndex+direction;
        if(insertLoc>size)
        {
            std::cout<<"无法找到合适的插入位置"<<std::endl;
            return false;
        }
        else if(pTree[insertLoc]!=0)
        {
            std::cout<<"插入节点位置为空"<<std::endl;
            return false;
        }
        else{
            pTree[insertLoc] = pNode;
            return true;
        }

    }
}
bool Tree::deleteNode(int nodeIndex, int *pNode) {
    if(nodeIndex<0||nodeIndex>size)
    {
        std::cout<<"删除节点位置不存在！"<<std::endl;
        return false;
    }
    else
    {
        *pNode = pTree[nodeIndex];
        pTree[nodeIndex] = 0;
        return true;
    }
}
int* Tree::searchNode(int nodeIndex) {
    if(nodeIndex<0||nodeIndex>size)
    {
        std::cout<<"删除节点不存在"<<std::endl;
        return nullptr;
    }
    else
    {
        return &pTree[nodeIndex];
    }
}
void Tree::treeTravers() {
    for(int i = 0;i<size;i++)
    {
        std::cout<<pTree[i]<<" ";
    }
    std::cout<<"\n";
}